package cn.com.bsoft.cloud.controller.his;

import cn.com.bsoft.cloud.entity.cloud.*;
import cn.com.bsoft.cloud.entity.param.PharmacistReviewParam;
import cn.com.bsoft.cloud.entity.param.PrescriptionDetailDTO;
import cn.com.bsoft.cloud.entity.param.PrescriptionDetailParam;
import cn.com.bsoft.cloud.service.HisInterface;
import cn.com.bsoft.cloud.utils.CompanyCode;
import cn.com.bsoft.cloud.utils.CompanyInterface;
import cn.com.bsoft.cloud.utils.HttpUtil;
import cn.com.bsoft.cloud.utils.ResultCode;
import cn.com.bsoft.cloud.ywkws.ChannelWSImplService;
import cn.com.bsoft.cloud.ywkws.Exception_Exception;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import groovy.util.logging.Log;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.Charset;
import java.util.*;

@RestController
public class CloudHisController {
    @Autowired
    private HisInterface hisInterface;
    @Autowired
    private CompanyInterface companyInterface;
    /**h
     *  his线上医生开处方通知平台
     * @return json
     */
    @RequestMapping("/onlinesendprescription")
    @ResponseBody
        public Map onlinesendprescription(@RequestBody Prescription prescription){
        List<Cfmesses> cfmessesList = prescription.getCfmessesList();
//        String cert = prescription.getCert();//公钥证书
//        String inData = prescription.getInData();//签名原文
        String patientphone = "";
        Map<String,String> resultMap = new HashMap<String, String>();
        try {
            String yyid = prescription.getAppointId();//预约ID
//            String caSign = prescription.getCaSign();//签名值
//            if(StringUtils.isBlank(caSign)){
//                resultMap.put("code",ResultCode.PARAMETERS_EMPTY);
//                resultMap.put("message","签名值不能为空");
//                return resultMap;
//            }else
//            if(StringUtils.isBlank(yyid)){
//                resultMap.put("code",ResultCode.PARAMETERS_EMPTY);
//                resultMap.put("message","预约ID不能为空");
//                return resultMap;
//            }else{
                if(StringUtils.isBlank(yyid)){
                    Map params = new HashMap();
                    String hisOrderNum = yyid;
                    String kfrq = "";
                    String cardNo = "";
                    String hospitalCode = "";
                    String deptCode = "";
                    for(int i=0;i<cfmessesList.size();i++){
                        Cfmesses  cfmesses= cfmessesList.get(i);
                        kfrq = cfmesses.getIssuerDate().substring(0,10);
                        cardNo = cfmesses.getPatient().getCardNum();
                        hospitalCode = cfmesses.getPatient().getHospitalCode();
                        deptCode = cfmesses.getCloudOfficeDeptCode();
                    }
                    params.put("begin",kfrq);
                    params.put("end",kfrq);
                    params.put("cardNo",cardNo);
                    params.put("hospitalCode",hospitalCode);
                    params.put("deptCode",deptCode);
                    params.put("hisOrderNum",null);
                    params.put("doctorNo",null);
                    params.put("status",null);
                    params.put("medicalSatisfaction",null);
                    params.put("overallSatisfaction",null);
                    params.put("yyid",null);
                    String paramsJson = JSON.toJSONString(params);
                    try {
                        Long timeStampValue = new Date().getTime()/1000;
                        String timeStamp = timeStampValue.toString();
                        String partherCode = "prescription";
                        String secret = "~(UKC3bBBPT*0kMOIybg";
                        String req = paramsJson+timeStamp+secret;
                        String sign = DigestUtils.sha256Hex(req.getBytes(Charset.forName("UTF-8")));
                        //测试地址http://172.16.5.35/test/schedule/queryScheduleRecordEx
                        //正式地址http://172.16.5.35/pay/schedule/queryScheduleRecordEx
                        String callbackUrl = "http://172.16.5.35/pay/schedule/queryScheduleRecordEx?partner="+partherCode+"&sign="+sign+"&timestamp="+timeStamp;;
                        String result = HttpUtil.doPost(callbackUrl, paramsJson);
                        JSONArray jsonArray = JSONArray.parseArray(result);
                        Map map = (Map)jsonArray.get(0);
                        String retyyid = map.get("recordID").toString();
                        yyid = retyyid;
                    }catch (Exception e){
                        e.printStackTrace();;
                    }

                }
                //判断YYID是否存在
                boolean yyidIsExists = hisInterface.yyidIsExists(yyid);
                if(yyidIsExists){
                    boolean yyidsfcz = hisInterface.yyidsfcz(yyid);
                    if(yyidsfcz) {
                        //不存在,调用医悟空接口
                        Appoint appoint = new Appoint();
                        String xml = "<Request><ApplicationId>5154567d3497401bb31d5d84866340e2</ApplicationId><ApplicationSecret>b2536bfe1f53424182da94e6d3250026</ApplicationSecret><Parameter><YyId>" + yyid + "</YyId></Parameter></Request>";
                        ChannelWSImplService service = new ChannelWSImplService();
                        String result = null;
                        try {
                            result = service.getChannelWSImplPort().queryAppointRecordsByYyId(xml);
                            System.out.println(result);
                            Document doc = Jsoup.parse(result, "UTF-8");
                            Elements mContent = doc.select("Record");
                            String ret_yyid = mContent.get(0).select("yyid").html();
                            appoint.setAppointId(ret_yyid);
                            String hospitalid = mContent.get(0).select("hospitalid").html();
                            appoint.setHospitalCode(hospitalid);
                            String hospitalname = mContent.get(0).select("hospitalname").html();
                            appoint.setHospitalName(hospitalname);
                            String workdate = mContent.get(0).select("workdate").html();
                            appoint.setAppointDate(workdate);
                            String xm = mContent.get(0).select("patientname").html();
                            appoint.setPatientName(xm);
                            String identity = mContent.get(0).select("patientid").html();
                            appoint.setIdentity(identity);
                            String sex = mContent.get(0).select("patientgender").html();
                            appoint.setSex(sex);
                            String ksdm = mContent.get(0).select("deptid").html();
                            appoint.setDepartmentCode(ksdm);
                            String ksmc = mContent.get(0).select("deptname").html();
                            appoint.setDepartmentName(ksmc);
                            String ysdm = mContent.get(0).select("doctorid").html();
                            appoint.setDoctorCode(ysdm);
                            String ysmc = mContent.get(0).select("doctorname").html();
                            appoint.setDoctorName(ysmc);
                            String starttime = mContent.get(0).select("starttime").html();
                            appoint.setAppointStartTime(starttime);
                            String endtime = mContent.get(0).select("endtime").html();
                            appoint.setAppointEndTime(endtime);
                            String appointstatus = mContent.get(0).select("appointstatus").html();
                            appoint.setAppointStatus(appointstatus);
                            String PatientTel = mContent.get(0).select("PatientTel").html();
                            patientphone = PatientTel;
//                            appoint.setCaSign(caSign);
//                            appoint.setCert(cert);
//                            appoint.setInData(inData);
                            //存储本地预约表
                            boolean appointInformationFlag = hisInterface.insertAppointInformation(appoint);
                            if (!appointInformationFlag) {
                                resultMap.put("code", ResultCode.ERROR);
                                resultMap.put("message", "预约信息插入失败！");
                                return resultMap;
                            }
                        } catch (Exception_Exception e) {
                            e.printStackTrace();
                            resultMap.put("code", ResultCode.ERROR);
                            resultMap.put("message", "医悟空报错" + e.getMessage());
                            return resultMap;
                        }
                    }
                            if(cfmessesList.size()>0){
                                for(int i=0;i<cfmessesList.size();i++){
                                    Cfmesses  cfmesses= cfmessesList.get(i);
                                    String prescriptionCode = cfmesses.getPrescriptionCode();
                                    if(StringUtils.isNotBlank(prescriptionCode)){
                                        String issuerDate = cfmesses.getIssuerDate();
                                        if(StringUtils.isNotBlank(issuerDate)){
                                            Doctor doctor = cfmesses.getDoctor();
                                            if(doctor == null){
                                                resultMap.put("code",ResultCode.ERROR);
                                                resultMap.put("message","医生信息不能为空！");
                                                return resultMap;
                                            }else{
                                                Patient patient = cfmesses.getPatient();
                                                if(null == patient){
                                                    resultMap.put("code",ResultCode.ERROR);
                                                    resultMap.put("message","患者信息不能为空！");
                                                    return resultMap;
                                                }else{
                                                    Diagnosemess diagnosemess = cfmesses.getDiagnosemess();
                                                    if(null == diagnosemess){
                                                        resultMap.put("code",ResultCode.ERROR);
                                                        resultMap.put("message","诊断信息不能为空！");
                                                        return resultMap;
                                                    }else{
                                                        List<Cfmess> cfmessList = cfmesses.getCfmessList();
                                                        if(cfmessList.size()<=0){
                                                            resultMap.put("code",ResultCode.ERROR);
                                                            resultMap.put("message","处方明细不能为空！");
                                                            return resultMap;
                                                        }else{
                                                            //插入处方列表
                                                            String uuid = UUID.randomUUID().toString().replace("-","");
                                                            String cfwyid = uuid+prescriptionCode;
                                                            boolean message = hisInterface.hisSendMessage(cfmesses, yyid,cfwyid,patientphone);
                                                            if(message){
                                                                boolean cfmxbatchInsertFlag = hisInterface.cfmxbatchInsert(cfmessList, cfwyid);
                                                                if(cfmxbatchInsertFlag){
                                                                    resultMap.put("code",ResultCode.SUCCESS);
                                                                    resultMap.put("message","存储成功！");
                                                                }else{
                                                                    resultMap.put("code",ResultCode.ERROR);
                                                                    resultMap.put("message","插入处方明细信息失败！");
                                                                    return resultMap;
                                                                }
                                                            }else{
                                                                resultMap.put("code",ResultCode.ERROR);
                                                                resultMap.put("message","插入处方信息失败！");
                                                                return resultMap;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }else{
                                            resultMap.put("code",ResultCode.ERROR);
                                            resultMap.put("message","处方开具时间不能为空！");
                                            return resultMap;
                                        }
                                    }else{
                                        resultMap.put("code",ResultCode.ERROR);
                                        resultMap.put("message","处方唯一编号不能为空！");
                                        return resultMap;
                                    }
                                }
                            }else{
                                resultMap.put("code",ResultCode.PARAMETERS_EMPTY);
                                resultMap.put("message","处方信息不能为空");
                                return resultMap;
                            }


                }else{
                    resultMap.put("code",ResultCode.ERROR);
                    resultMap.put("message","处方平台已经存在该条记录，请勿重复提交！");
                    return resultMap;
                }
//            }
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("code",ResultCode.ERROR);
            resultMap.put("message",e.getMessage());
            return resultMap;
        }
        return resultMap;
    }

    /**
     *更新处方表签名
     */
    @PostMapping("/pharmacistReview")
    public Map updateCaSgin(@RequestBody PharmacistReviewParam pharmacistReviewParam){
//        System.out.println("pharmacistReviewParam="+pharmacistReviewParam.toString());
        Map<String,String> resultMap = new HashMap<String, String>();
        boolean result = hisInterface.updateCaSgin(pharmacistReviewParam.getPrescriptionCode(),pharmacistReviewParam.getCaSign());
        if(result){
            resultMap.put("code",ResultCode.SUCCESS);
            resultMap.put("message","更新成功");
            return resultMap;
        }
        resultMap.put("code",ResultCode.ERROR);
        resultMap.put("message","更新失败");
        return resultMap;
    }
    /**
     *his调用平台接口修改支付状态
     * @return json
     */
    @RequestMapping("/updatePayStatus")
    @ResponseBody
    public Map updatePayStatus(@RequestBody UpdatePayStatus updatePayStatus){
        Map<String,String> resultMap = new HashMap<String, String>();
        try{
            String status = updatePayStatus.getStatus();//支付状态
            String hospitalCode = updatePayStatus.getHospitalCode();//医院代码
            List prescriptionCodes = updatePayStatus.getPrescriptionCode();//处方ID
            if(StringUtils.isBlank(status)){
                resultMap.put("code",ResultCode.PARAMETERS_EMPTY);
                resultMap.put("message","支付状态不能为空！");
                return resultMap;
            }else if(StringUtils.isBlank(hospitalCode)){
                resultMap.put("code",ResultCode.PARAMETERS_EMPTY);
                resultMap.put("message","医院代码不能为空！");
                return resultMap;
            }else if(prescriptionCodes==null||(prescriptionCodes!=null&&prescriptionCodes.size()==0)){
                resultMap.put("code",ResultCode.PARAMETERS_EMPTY);
                resultMap.put("message","处方ID不能为空！");
                return resultMap;
            }else{
                if("5".equals(status)){
                    boolean isSendDrugs = hisInterface.sendDrugs(hospitalCode,prescriptionCodes);
                    if(isSendDrugs){
                        resultMap.put("code", ResultCode.SUCCESS);
                        resultMap.put("msg", "操作成功！");
                        return resultMap;
                    }else{
                        resultMap.put("code",ResultCode.ERROR);
                        resultMap.put("message","更新处方列表状态失败！");
                        return resultMap;
                    }
                }else{
                    for(int i=0;i<prescriptionCodes.size();i++){
                        int onePrescriptionIsExists = hisInterface.onePrescriptionIsExists(hospitalCode,prescriptionCodes.get(i).toString());
                        if(onePrescriptionIsExists == 0){
                            resultMap.put("code",ResultCode.ERROR);
                            resultMap.put("message",prescriptionCodes.get(i).toString()+"在捷医云诊室中不存在，请核对！");
                            return resultMap;
                        }
                    }
                    int prescriptionIsDelete = hisInterface.prescriptionIsDelete(hospitalCode,prescriptionCodes);
                    if(prescriptionIsDelete>0){
                        resultMap.put("code",ResultCode.ERROR);
                        resultMap.put("message","处方已经作废不能支付!");
                        return resultMap;
                    }else{
                        int prescriptionIsSend = hisInterface.prescriptionIsSend(hospitalCode,prescriptionCodes);
                        if(prescriptionIsSend>0){
                            if(prescriptionCodes.size()==prescriptionIsSend){
                                    //判断国药上药
                                    String companyCode = hisInterface.queryCompanyCode(updatePayStatus);
                                    if(companyCode.equals(CompanyCode.GUOYAO)){
                                        return companyInterface.guoYao(updatePayStatus,companyCode);
                                    }else{
                                        return companyInterface.shangYao(updatePayStatus,companyCode);
                                    }
                            }else{
                                resultMap.put("code",ResultCode.ERROR);
                                resultMap.put("message","医药公司发药条数于His支付条数不一致!");
                                return resultMap;
                            }
                        }else{
                            resultMap.put("code",ResultCode.ERROR);
                            resultMap.put("message","药品未到达配送点不能支付!");
                            return resultMap;
                        }
                    }
                }
            }
        }catch (Exception e){
            resultMap.put("code",ResultCode.ERROR);
            resultMap.put("message","更改失败！"+e.getMessage());
            return resultMap;
        }
    }
    /**
     * his调用平台接口作废处方
     * @return
     */
    @ResponseBody
    @RequestMapping("/invalidprescription")
    public Map<String,Object> querySitesByCode(@RequestBody InvalidPrescription invalidPrescription){
        Map<String,Object> regMsg=new HashMap<String, Object>();
        try {
            String hoscode=invalidPrescription.getHospitalCode();//医院代码
            List prescriptionCodes =invalidPrescription.getPrescriptionCode();//处方ID列表
            if (StringUtils.isBlank(hoscode)) {
                regMsg.put("code", ResultCode.PARAMETERS_EMPTY);
                regMsg.put("msg", "医院编码不能为空");
                return regMsg;
            }else if(prescriptionCodes==null||(prescriptionCodes!=null&&prescriptionCodes.size()==0)){
                regMsg.put("code", ResultCode.PARAMETERS_EMPTY);
                regMsg.put("msg", "处方ID不能为空");
                return regMsg;
            }else{
                int prescriptionIsExists = hisInterface.prescriptionIsExists(hoscode,prescriptionCodes);//处方是否存在
                if (prescriptionIsExists<=0){
                    regMsg.put("code", ResultCode.ERROR);
                    regMsg.put("msg", "未查到改处方，请核对数据！");
                }else {
                    int deliveryStatus = hisInterface.queryDeliveryStatus(hoscode,prescriptionCodes);//配药状态
                    if(deliveryStatus!=0){
                        regMsg.put("code", ResultCode.ERROR);
                        regMsg.put("msg", "该处方医药公司已经配送不能作废！");
                    }else{
                        int prescriptionIsPayed = hisInterface.prescriptionIsPayed(hoscode,prescriptionCodes);
                        if(prescriptionIsPayed!=0){
                            regMsg.put("code", ResultCode.ERROR);
                            regMsg.put("msg", "该处方已经支付不能作废！");
                        }else{
                            hisInterface.invalidPrescription(hoscode,prescriptionCodes);
                            regMsg.put("code", ResultCode.SUCCESS);
                            regMsg.put("msg", "操作成功！");
                        }
                    }
                }
            }

        } catch (Exception e) {
            regMsg.put("code", ResultCode.ERROR);
            regMsg.put("msg", "请求出错");
            regMsg.put("error", e.getMessage());
        }
        return regMsg;
    }
    /**
     * his调用平台接口查询处方到达配送点信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/prescriptionStatus")
    public prescriptionStatusRsp queryPrescriptionStatus(@RequestBody InvalidPrescription invalidPrescription){
        List<prescriptionStatusResult> prescriptionStatusResultRecords = new ArrayList<prescriptionStatusResult>();
        prescriptionStatusRsp prescriptionStatusRsp= new prescriptionStatusRsp();
        String hoscode=invalidPrescription.getHospitalCode();//医院代码
        List prescriptionCodes =invalidPrescription.getPrescriptionCode();//处方ID列表
        if (StringUtils.isBlank(hoscode)) {
            prescriptionStatusRsp.setCode(ResultCode.PARAMETERS_EMPTY);
            prescriptionStatusRsp.setMessage("医院编码不能为空");
            return prescriptionStatusRsp;
        }else if(prescriptionCodes==null||(prescriptionCodes!=null&&prescriptionCodes.size()==0)){
            prescriptionStatusRsp.setCode(ResultCode.PARAMETERS_EMPTY);
            prescriptionStatusRsp.setMessage("处方ID不能为空");
            return prescriptionStatusRsp;
        }else{
            try{
                for(int i=0;i<prescriptionCodes.size();i++){
                    String prescriptionCode = prescriptionCodes.get(i).toString();
                    int isArrived = hisInterface.prescriptionIsArrived(prescriptionCode,hoscode);
                    if(isArrived>0){
                        prescriptionArriveResult prescriptionArriveResult = hisInterface.prescriptionArrived(prescriptionCode,hoscode);
                        prescriptionStatusResult prescriptionStatusResult = new prescriptionStatusResult();
                        if("2".equals(prescriptionArriveResult.getDeliveryStatus())){
                            prescriptionStatusResult.setPsdbm(prescriptionArriveResult.getPsdbm());
                            prescriptionStatusResult.setArrivalTime(prescriptionArriveResult.getArrivedTime());
                            prescriptionStatusResult.setArrive("1");
                            prescriptionStatusResult.setHisPrescriptionCode(prescriptionCode);
                            prescriptionStatusResultRecords.add(prescriptionStatusResult);
                        }else{
                            prescriptionStatusResult.setPsdbm("");
                            prescriptionStatusResult.setArrivalTime("");
                            prescriptionStatusResult.setArrive("0");
                            prescriptionStatusResult.setHisPrescriptionCode(prescriptionCode);
                            prescriptionStatusResultRecords.add(prescriptionStatusResult);
                        }

                    }else{
                        prescriptionStatusResult prescriptionStatusResult = new prescriptionStatusResult();
                        prescriptionStatusResult.setArrive("0");
                        prescriptionStatusResult.setArrivalTime("");
                        prescriptionStatusResult.setPsdbm("");
                        prescriptionStatusResult.setHisPrescriptionCode(prescriptionCode);
                        prescriptionStatusResultRecords.add(prescriptionStatusResult);
                    }
                }
                prescriptionStatusRsp.setCode(ResultCode.SUCCESS);
                prescriptionStatusRsp.setMessage("请求成功！");
                prescriptionStatusRsp.setPrescriptionStatusResult(prescriptionStatusResultRecords);
            }catch (Exception e){
                e.printStackTrace();
                prescriptionStatusRsp.setCode(ResultCode.ERROR);
                prescriptionStatusRsp.setMessage(e.getMessage());
                return prescriptionStatusRsp;
            }
        }
        return prescriptionStatusRsp;
    }

    @ResponseBody
    @RequestMapping("/api/query/prescription/detail/list")
    public Map<String, Object> queryPrescriptionDetailList(@RequestBody PrescriptionDetailParam prescriptionDetail) {

        Map<String, Object> regMsg = new HashMap<String, Object>();
        try {
            List<PrescriptionDetailDTO> prescriptionDetailList = hisInterface.queryPrescriptionDetail(prescriptionDetail);
            regMsg.put("code", 1);
            regMsg.put("result", prescriptionDetailList);
            regMsg.put("msg", "查询复诊处方列表成功！");
        } catch (Exception e) {
            e.printStackTrace();
            regMsg.put("code", 0);
            regMsg.put("msg", "查询复诊处方列表失败！" + e.getMessage());
            String message = "查询复诊处方";
        }
        return regMsg;
    }


}
